﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AESUtil
{
    internal class JsonUtil
    {
        
        public static string ConvertFormatJsonString(string str)
        {
            if (Properties.Settings.Default.autoFormat && str != null && str.Length>0)
            {
                try
                {
                    //格式化json字符串
                    JsonSerializer serializer = new JsonSerializer();
                    TextReader tr = new StringReader(str);
                    JsonTextReader jtr = new JsonTextReader(tr);
                    object obj = serializer.Deserialize(jtr);
                    if (obj != null)
                    {
                        StringWriter textWriter = new StringWriter();
                        JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                        {
                            Formatting = Newtonsoft.Json.Formatting.Indented,
                            Indentation = 4,
                            IndentChar = ' '
                        };
                        serializer.Serialize(jsonWriter, obj);
                        return textWriter.ToString();
                    }
                    else
                    {
                        return str;
                    }
                }
                catch
                {
                    return str;
                }

            }
            else
            {
                return str;
            }
        }
        public static string ConvertOriJsonString(string str)
        {
            if (Properties.Settings.Default.autoFormat)
            {
                //格式化json字符串
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(str);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Newtonsoft.Json.Formatting.None,
                        Indentation = 0,
                        IndentChar = ' '
                    };
                    serializer.Serialize(jsonWriter, obj);
                    return textWriter.ToString();
                }
                else
                {
                    return str;
                }
            }
            else
            {
                return str;
            }
        }
    }
}
